package com.nit.lab.utils;

import java.sql.*;

public class DBConn {
	// 定义MySQL数据库连接信息
	private final static String driverName = "com.mysql.jdbc.Driver";
	private final static String dbURL = "jdbc:mysql://112.74.197.205/coolprint?useUnicode=true&characterEncoding=UTF-8";
	private final static String userName = "root";
	private final static String userPwd = "17857021372";

	private static Connection conn ;

	// 加载数据库驱动
	static {
		try {
			Class.forName(driverName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	// 获取数据库连接
	public static Connection getConn() {
		try {
			if(conn == null){
				conn = DriverManager.getConnection(dbURL, userName, userPwd);
				System.out.println("数据库连接创建成功！");
			}
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			System.out.println("数据库连接创建失败！");
		}
		return null;
	}

	// 释放资源，关闭数据库连接
	public static void closeConn(ResultSet rs, Statement stmt, PreparedStatement prestmt, CallableStatement cstmt,
			Connection conn) {
		try {
			if (rs != null) {
				rs.close();
			}
			rs = null;
			if (stmt != null) {
				stmt.close();
			}
			stmt = null;
			if (prestmt != null) {
				prestmt.close();
			}
			prestmt = null;
			if (cstmt != null) {
				cstmt.close();
			}
			cstmt = null;
			if (conn != null) {
				conn.close();
			}
			conn = null;
			System.out.println("数据库连接释放成功！");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("数据库连接释放失败！");
		}
	}
}
